<?php

class MyController extends CController
{

    public $layout         = '//layouts/main';
    public $menu           = array();
    public $assetDir; //Khoi tao bien assetDir
    public $breadcrumbs    = array();
    public $categories;
    public $meta_desc;
    public $meta_keywords;
    public $lang_id        = null;
    public $slide_post;
    public $main_services;
    public $sub_services;
    public $highlights_post;
    // Model User
    public $user           = NULL;
    public $modelName      = '';
    public $model          = '';
    // Menu hiển thị nội bộ trong Controller
    public $controllerMenu = array();
    // Menu chính bên tay trái
    public $sidebarMenu    = array();
    // Role
    public $userRole       = '';
    public $isAdmin        = FALSE;
    public $isBussiness    = FALSE;
    public $isStaff        = FALSE;
    public $isCustomer     = FALSE;
    public $isBranch       = FALSE;
    //Active Menu
    public $menuActive     = '';
    public $search         = false;
    public $currentLimit   = 20;

    /**
     * @return array action filters
     */
    public function filters()
    {
        return array(
            'accessControl',
        );
    }

    /**
     * Specifies the access control rules.
     * This method is used by the 'accessControl' filter.
     * @return array access control rules
     */
    public function accessRules()
    {
        return array(
            array('allow', // allow all users to access 'index' and 'view' actions.
                'controllers' => array('site', 'user', 'book', 'subscribe'),
                'actions'     => array(
                    'login', 'error', 'signup', 'forgotPassword', 'captcha', 'resetPassword', 'admin', 'concierge',
                    'form', // Book form
                    'getService', // Book form
                    'getServiceDuration' // Book form
                ),
                'users'       => array('?'),
            ),
            array('allow', // allow authenticated users to access all actions
                'users' => array('@'),
            ),
            array('deny', // deny all users
                'users' => array('?'),
            ),
        );
    }

    public function init()
    {
        parent::init();

        if (isset($_POST['language']))
        {
            $lang               = $_POST['language'];
            $MultilangReturnUrl = $_POST[$lang];
            $this->redirect($MultilangReturnUrl);
        }
        // Set the application language if provided by GET, session or cookie
        if (isset($_GET['language']))
        {
            Yii::app()->language = $_GET['language'];
            Yii::app()->user->setState('language', $_GET['language']);
            $this->createCookie('language', $_GET['language']);
        }
        else if (Yii::app()->user->hasState('language'))
        {
            Yii::app()->language = Yii::app()->user->getState('language');
        }
        else if (isset(Yii::app()->request->cookies['language']))
        {
            Yii::app()->language = Yii::app()->request->cookies['language']->value;
        }

        //Gan bien baseUrl vao bien assetDir
        $this->assetDir = Yii::app()->theme->baseUrl . '/assets/';

        Yii::app()->user->setReturnUrl(array('site/index'));

        // Thiết lập menu
        $this->_setSideMenu();

        // Thiết lập user đăng nhập
        if (Yii::app()->user->isGuest == FALSE)
        {
            $this->user = Yii::app()->user->getCurrentUser();
        }

        $auth           = Yii::app()->authManager;
        $roles          = $auth->getRoles(Yii::app()->user->id);
        $this->userRole = (@current($roles)->name) ? @current($roles)->name : Users::TYPE_CUSTOMER;

        $this->isAdmin     = ($this->userRole == Users::TYPE_ADMIN) ? TRUE : FALSE;
        $this->isBussiness = ($this->userRole == Users::TYPE_BUSINESS) ? TRUE : FALSE;
        $this->isStaff     = ($this->userRole == Users::TYPE_STAFF) ? TRUE : FALSE;
        $this->isCustomer  = ($this->userRole == Users::TYPE_CUSTOMER) ? TRUE : FALSE;
        $this->isBranch    = ($this->userRole == Users::TYPE_BUSINESS && $this->user->author_id != Users::SUPER_ADMIN) ? TRUE : FALSE;
        $this->menuActive  = Yii::app()->controller->id;
    }

    /**
     * Thiết lập hiển thị menu bên cạnh
     */
    private function _setSideMenu()
    {
        if (!Yii::app()->user->isGuest)
        {
            $this->sidebarMenu = require 'MainMenu.php';
        }
    }

    /**
     * Kiềm tra quyền truy cập
     * @param string $action Tên của hành động cần thực hiện
     * @return boolean
     * @throws CHttpException
     */
    protected function checkAccess($action = '', $controller = '', $return = FALSE)
    {
        // Lấy tên controller và tên action
        $con = $controller != '' ? ucfirst($controller) : ucfirst(Yii::app()->controller->id);
        $act = $action != '' ? ucfirst($action) : ucfirst(Yii::app()->controller->action->id);

        if ($return)
            return Users::checkAccess($act, $con);

        if (Users::checkAccess($act, $con))
            return TRUE;
        else
        {
            if (Yii::app()->user->isGuest)
            {
                $this->redirect(array('site/login'));
            }
            else
            {
                $this->permissionException();
            }
        }
    }

    public function permissionException()
    {
        throw new CHttpException(400, Yii::t('yii', 'You are not authorized to perform this action.'));
    }

    /**
     * 
     * @param type $dir
     * @param type $size_w
     * @param type $size_h
     * @param type $name
     * @return string
     */
    protected function _uploadPhoto($dir, $size_w = 320, $size_h = 320, $name = 'file')
    {
        if (@$_FILES[$name])
        {
            $file     = $_FILES[$name];
            $tmp_file = "files/$dir/" . md5(time() . $file['name']) . "_" . $file['name'];
            if (move_uploaded_file($file['tmp_name'], $tmp_file))
            {
                $thumb = Yii::app()->phpThumb->create($tmp_file);
                $thumb->adaptiveResize($size_w, $size_h);
                $thumb->save($tmp_file);
                return $tmp_file;
            }
            else
            {
                return FALSE;
            }
        }
        return FALSE;
    }

    public function createMultilanguageReturnUrl($lang = 'nl')
    {
        if (count($_GET) > 0)
        {
            $arr             = $_GET;
            $arr['language'] = $lang;
        }
        else
        {
            $arr = array('language' => $lang);
        }

        return $this->createUrl('', $arr);
    }

    /**
     * Creates a popularity cookie with a specific duration set in Yii params.
     */
    public function createCookie($name, $value)
    {
        $cookie                             = new CHttpCookie($name, $value);
        $cookie->expire                     = time() + Yii::app()->params['cookieDuration'];
        Yii::app()->request->cookies[$name] = $cookie;
    }

}
